package com.huatai.common.util;

import com.huatai.common.config.JwtProperties;
import com.huatai.common.entity.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.servlet.http.HttpServletRequest;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @program: ht-system
 * @description: 获取用户登录基本信息
 * @author: songxiude
 * @create: 2023-02-08 14:54
 **/
public class AuthUtil {

	public AuthUtil() {
	}

	/**
	 * 获取用户信息
	 * @return
	 */
	public static UserInfo getUser(){
		HttpServletRequest request = WebUtil.getRequest();
		if (request == null) {
			return null;
		}
		UserInfo userInfo=new UserInfo();
		String token = request.getHeader("Authorization");
		//String tokenkey = StringUtils.substring(token, 7);
		String tokenkey = token.replace("bearer ", "");
		if (StringUtil.isBlank(tokenkey)) {
			throw new RuntimeException("缺失令牌,鉴权失败");
		}
		Claims claims = getClaims(tokenkey);
		if(claims==null){
			throw new RuntimeException("请求未授权");
		}

		userInfo.setUserId(Func.toLong(claims.get("user_id")));
		userInfo.setName(Func.toStr(claims.get("name")));
		userInfo.setCode(Func.toStr(claims.get("user_code")));
		userInfo.setAccount(Func.toStr(claims.get("username")));
		userInfo.setDeptId(Func.toLong(claims.get("dept_id")));
		userInfo.setPostId(Func.toLong(claims.get("post_id")));
		userInfo.setRealName(Func.toStr(claims.get("real_name")));
		userInfo.setIsAdmin(Func.toInt(claims.get("is_admin")));
		return userInfo;
	}

	/**
	 * 获取Claims对象
	 * @param token
	 * @return
	 */
	public static Claims getClaims(String token){
		//return Jwts.parser().setSigningKey(JwtProperties.getTokenKey().getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token).getBody();
		try {
			return Jwts.parser().setSigningKey(JwtProperties.getTokenKey().getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token).getBody();
		}catch (Exception e){
			System.out.println(e.getMessage());
			return null;
		}
	}
}
